<template>
  <div>
    <div class="saveButton">
      <Button size="small" type="primary" @click="saveParameter">保存</Button>
    </div>
    <Card :bordered="false" :dis-hover="true">
      <Form
        label-position="right"
        :label-width="150"
        :model="parameter"
        :rules="parameterValidate"
        ref="parameter"
      >
        <FormItem label="Webhook" prop="value.WEBHOOK">
          <Input
            v-model="parameter.value.WEBHOOK"
            placeholder="请输入Webhook"
          />
        </FormItem>
        <FormItem label="密钥" prop="value.SECRET">
          <Input
            v-model="parameter.value.SECRET"
            type="password"
            password
            placeholder="请输入密钥"
          />
        </FormItem>
      </Form>
    </Card>
  </div>
</template>
<script>
import {
  getParameters,
  createParameter,
  updateParameter,
} from "@/api/HttpAutoTestService/parameter";
export default {
  name: "dingtalk",
  mounted() {
    getParameters({ key: "DINGTALK" }).then((res) => {
      const data = res.data;
      let results = data.results;
      if (results.length > 0) {
        this.parameter.id = results[0].id;
        this.parameter.name = results[0].name;
        this.parameter.key = results[0].key;
        this.parameter.value = JSON.parse(results[0].value);
      }
    });
  },
  data() {
    return {
      parameter: {
        id: "",
        name: "钉钉",
        key: "DINGTALK",
        value: {
          WEBHOOK: "",
          SECRET: "",
        },
      },
      parameterValidate: {
        "value.WEBHOOK": [
          { required: true, message: "必填项", trigger: "blur" },
        ],
        "value.SECRET": [
          { required: true, message: "必填项", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    saveParameter() {
      let parameter = {
        id: this.parameter.id,
        name: this.parameter.name,
        key: this.parameter.key,
        value: JSON.stringify(this.parameter.value),
      };
      this.$refs["parameter"].validate((valid) => {
        if (valid) {
          if (parameter.id) {
            updateParameter(parameter).then((res) => {
              this.$Message.info("保存成功");
            });
          } else {
            delete parameter["id"];
            createParameter(parameter).then((res) => {
              if (res.status === 201) {
                this.parameter.id = res.data.id;
                this.$Message.info("保存成功");
              }
            });
          }
        }
      });
    },
  },
};
</script>
<style scoped>
.saveButton {
  display: flex;
  justify-content: flex-end;
}
</style>
